package com.qianfeng.smartplatform.events.listeners;

import com.qianfeng.smartplatform.events.DeviceOnOffLineEvent;
import com.qianfeng.smartplatform.pojo.Device;
import com.qianfeng.smartplatform.service.DeviceService;
import com.qianfeng.smartplatform.utils.RequestUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

@Component
public class DeviceStatusChangeListener {
    private DeviceService deviceService;

    @Autowired
    public void setDeviceService(DeviceService deviceService) {
        this.deviceService = deviceService;
    }

    @EventListener
    @Async
    public void onEvent(DeviceOnOffLineEvent event) {
        System.err.println("登录的ip"+event.getIp());
        Device device = new Device();
        device.setCurrentConnectIp(event.getIp());
        device.setDeviceId(event.getId());//设置设备的id
        device.setIsOnline(event.getStatus());//设置状态
        device.setConnectTime(event.getEventTime());//设置连接时间
        device.setLostConnectTime(event.getEventTime());//设置断开时间, 两个都设置的原因是因为我们只需要一个数据,是根据状态选择的,所以即便设置两个也只会用一个
        if (StringUtils.hasText(event.getIp())) {//如果是登录的时候有ip才会设置登录的区域
            device.setConnectLocation(RequestUtil.getLocationByIp(event.getIp()));
        }
        deviceService.updateDeviceOnlineStaus(device);
    }
}


